package com.sktk.keepAccount.exception;

import com.alibaba.fastjson.JSON;
import com.sktk.keepAccount.common.core.exception.BaseException;
import com.sktk.keepAccount.common.core.exception.SystemErrorType;
import com.sktk.keepAccount.common.core.vo.Result;
import com.sktk.keepAccount.common.web.exception.DefaultGlobalExceptionHandlerAdvice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandlerAdvice extends DefaultGlobalExceptionHandlerAdvice {

    /**
     * 处理 json 请求体调用接口校验失败抛出的异常
     * https://blog.csdn.net/weixin_43702146/article/details/121035514
     *
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public String methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) throws Exception {

        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());

        return Result.fail(SystemErrorType.BUSINESS_ERROR, collect.get(0));
    }
}